package pers.qianyu.month_202011.date_20201117;

/**
 * 714. 买卖股票的最佳时机含手续费
 * https://leetcode-cn.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee/
 *
 * @author mizzle rain
 * @date 2020-11-17 17:13
 */
public class MaxProfitWithServiceCharge {
    public static void main(String[] args) {
        int[] prices = {1, 3, 2, 8, 4, 9};
        int fee = 2;
        int result = new MaxProfitWithServiceCharge().maxProfit(prices, fee);
        System.out.println("result = " + result);
    }

    public int maxProfit(int[] prices, int fee) {
        if (prices == null || prices.length == 0) {
            return 0;
        }
        int[][] dp = new int[prices.length][2];
        dp[0][0] = 0;
        dp[0][1] = -prices[0] - fee;
        for (int i = 1; i < prices.length; i++) {
            // 今天手里没有股票：1、昨天手里没有，今天也没买 2、昨天手里有，今天卖了
            dp[i][0] = Math.max(dp[i - 1][0], dp[i - 1][1] + prices[i]);
            // 今天手里有股票：1、昨天手里有 2、昨天手里没有，今天买了
            dp[i][1] = Math.max(dp[i - 1][1], dp[i - 1][0] - prices[i] - fee);
        }
        return dp[prices.length - 1][0];
    }

    /**
     * 优化空间
     */
    public int maxProfit2(int[] prices, int fee) {
        if (prices == null || prices.length == 0) {
            return 0;
        }
        int a = 0, b = -prices[0] - fee;
        for (int i = 1; i < prices.length; i++) {
            int newA = Math.max(a, b + prices[i]);
            int newB = Math.max(b, a - prices[i] - fee);
            a = newA;
            b = newB;
        }
        return a;
    }
}
